﻿@using System.Text.Json.Nodes
@using FormBuilder.DefaultTemplate
@using FormBuilder.Models
@using FormBuilder.Components.Form
@using FormBuilder.Services
@using FormBuilder.Stores
@using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage

<RadzenDialog />

@if(Context != null)
{
    <FormViewer IsEditModeEnabled=false IsNavigationDisplayed=true Context=@Context></FormViewer>
}

@code {
    [Parameter] public List<FormRecord> FormRecords { get; set; }
    [Parameter] public WorkflowRecord Workflow { get; set; }
    [Parameter] public JsonObject Input { get; set; }
    [Parameter] public AntiforgeryTokenRecord AntiforgeryToken { get; set; }
    [Parameter] public string CurrentStepId { get; set; }
    [Parameter] public List<string> ErrorMessages { get; set; }
    [Parameter] public List<string> SuccessMessages { get; set; }
    [Parameter] public List<string> SupportedLanguageCodes { get; set; }
    [Parameter] public Template Template { get; set; }
    [Inject] public IJSRuntime jsRuntime { get; set; }
    [Inject] private INavigationHistoryService navigationHistoryService { get; set; }
    private WorkflowContext Context { get; set; }

    [JSInvokable]
    public void SetErrorMessage(string errorMessage)
    {
        Context.Execution.ErrorMessages = new List<string>
        {
            errorMessage
        };
        StateHasChanged();
    }

    [JSInvokable]
    public void SetSuccessMessage(string successMessage)
    {
        Context.Execution.SuccessMessages = new List<string>
        {
            successMessage
        };
        StateHasChanged();
    }

    [JSInvokable]
    public void SetInputData(string key, string value)
    {
        if(Input.ContainsKey(key)) Input[key] = value;
        else Input.Add(key, value);
        StateHasChanged();
    }

    [JSInvokable]
    public void ClearErrorMessages()
    {
        Context.Execution.ErrorMessages = new List<string>();
        StateHasChanged();
    }

    [JSInvokable]
    public void Navigate(string eltId, string key, string value)
    {
        var stepExecution = Context.GetCurrentStepExecution();
        var linkExecution = Context.GetLinkExecutionFromFormEltAndCurrentStep(eltId);
        var linkDefinition = Context.Definition.Workflow.Links.Single(l => l.Id == linkExecution.LinkId);
        var obj = new JsonObject();
        if(linkExecution.OutputData != null) obj = linkExecution.OutputData.AsObject();
        obj.Add(key, value);
        linkExecution.OutputData = obj;
        Context.NextStep(linkDefinition);
        StateHasChanged();
    }

    protected override void OnParametersSet()
    {
        base.OnParametersSet();
        if (Context == null)
        {
            var step = Workflow?.Steps?.SingleOrDefault(s => s.Id == CurrentStepId);
            Context = WorkflowContext.CreateWorkflow(Workflow, FormRecords, CurrentStepId, ErrorMessages, SuccessMessages, AntiforgeryToken, Input, SupportedLanguageCodes, Template);
        }
    } 

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);
        if(firstRender)
        {
            await navigationHistoryService.SaveCurrentStep(Context);
            try
            {                
                await jsRuntime.InvokeVoidAsync("setCsharpReference", DotNetObjectReference.Create(this));
            }
            catch(Exception) { }
        }
    }
}